<?php
/*
Extension Name: Vanilla Packer
Extension Url: http://code.google.com/p/vanilla-packer/
Description: Merge js and css files in one file
Version: 0.4.beta.4
Author: DinoBoff
Author Url: http://lussumo.com/community/account/2469/
Support: DinoBoff At Hotmail dot com
*/

define('PACKER_DIR', dirname(__FILE__));

$Context->SetDefinition('ExtensionOptions', 'Extension options');

$Context->SetDefinition('PackerSettings', 'js/css packer settings');
$Context->SetDefinition('PackerSettingsNotes', 'This feature is experimental. You shouldn\'t use it on a live forum.' );
$Context->SetDefinition('PackerOn', 'Turn on/off the packer.');
$Context->SetDefinition('PackerOnNotes', '! Turning on and off the packer here or on the extension page might not be enought if you get some trouble with feature. To get ride of the patch you need to reinstall the files this patch has replaced.');
$Context->SetDefinition('PackerDisableGzip', 'Disable Gzip compression.');
$Context->SetDefinition('PackerDisableGzipNotes', 'The packer try to figure out if your server has the Zlib library. Use this option to stop the merger using it.');

$Context->SetDefinition('PackerCheckPatch', 'Patch Checker');
$Context->SetDefinition('PackerCheckInstallation', 'Patch installation');
$Context->SetDefinition('PackerIconAlert', 'Alert');
$Context->SetDefinition('PackerIconCheck', 'Checked');
$Context->SetDefinition('PackerInstallationError', 'The patch is not installed properly. The following files need to be patch again:');
$Context->SetDefinition('PackerUptoDate', 'The patch has been installed properly.');

$Context->SetDefinition('PackerCheckStyle', 'Styles Checker');
$Context->SetDefinition('PackerCheckStyleNotes', 'Check that all your styles contain a cache folder and the css packer.');
$Context->SetDefinition('PackerCacheOk', 'Contain the cache folder.');
$Context->SetDefinition('PackerPackerOk', 'Contain the css packer.');
$Context->SetDefinition('PackerNoStyleCache', 'No cache folder.');
$Context->SetDefinition('PackerStyleCacheNotWritable', 'Cache folder not writable.');
$Context->SetDefinition('PackerNoStylePacker', 'No css packer.');
$Context->SetDefinition('Packer_WrongPacker', 'Not a valid or up-to-date css packer');

$Context->SetDefinition('PackerCheckJS', 'JS checker');
$Context->SetDefinition('PackerNoJSCache', 'No cache folder in the js folder.');
$Context->SetDefinition('PackerJSCacheNotWritable', 'The js/cache/ is not writable.');
$Context->SetDefinition('PackerJSCacheOk', 'js/cache/ is writable.');


if ($Context->SelfUrl == "settings.php") {
	
	class CheckPackerInstallation {
		var $Context;
		var $Name;
		var $_Styles;
		var $Styles;
		var $MD5Error;
		var $JSCache;
		
		function CheckPackerInstallation(&$Context){
			$this->Name = 'CheckPackerInstallation';
			$this->Context = &$Context;
			$Configuration['PACKER_MD5'] = array();
			include(PACKER_DIR . '/md5.php');
			$this->Context->Configuration['PACKER_MD5'] = $Configuration['PACKER_MD5'];
			$this->CheckStyles();
			$this->CheckMD5();
			$this->CheckJSCache();
		}
		
		function CheckStyles(){
			$this->DefineStyles($this->Context->Configuration['THEME_PATH']);
			$this->Styles = array();
			foreach ($this->_Styles as $Style) {
				$this->Styles[$Style] = array();
				$cache = $this->Context->Configuration['THEME_PATH'] . 'styles/' . $Style . '/cache';
				$packer = $this->Context->Configuration['THEME_PATH'] . 'styles/' . $Style . '/packer.php';
				if (!file_exists($cache) || !is_dir($cache)){
					$this->Styles[$Style]['cache'] = array('error' => 1, 'message' => $this->Context->GetDefinition('PackerNoStyleCache'));
				} elseif (!is_writable($cache)) {
					$this->Styles[$Style]['cache'] = array('error' => 1, 'message' => $this->Context->GetDefinition('PackerStyleCacheNotWritable'));
				} else {
					$this->Styles[$Style]['cache'] = array('error' => 0, 'message' => '');
				}
				if(!file_exists($packer)){
					$this->Styles[$Style]['packer'] = array('error' => 1, 'message' => $this->Context->GetDefinition('PackerNoStylePacker'));
				} elseif (md5_file($packer) != $this->Context->Configuration['PACKER_MD5']['themes/vanilla/styles/default/packer.php']) {
					$this->Styles[$Style]['packer'] = array('error' => 1, 'message' => $this->Context->GetDefinition('Packer_WrongPacker'));
				} else {
					$this->Styles[$Style]['packer'] = array('error' => 0, 'message' => '');
				}
			}	
		}
		
		function CheckMD5(){
			$this->MD5Error = array();
			foreach ($this->Context->Configuration['PACKER_MD5'] as $file => $md5) {
				if(ereg('^library/.*$', $file)){
					$path = eregi_replace('^library/', $this->Context->Configuration['LIBRARY_PATH'], $file);
				} else {
					$path = $this->Context->Configuration['APPLICATION_PATH'] . $file;
				}
				if ($md5 != md5_file($path)){
					$this->MD5Error[] = $file;
				}
			}
			
		}
		
		function CheckJSCache(){
			$cache = $this->Context->Configuration['APPLICATION_PATH'] . 'js/cache';
			if (!file_exists($cache) || !is_dir($cache)){
				$this->JSCache = -1;
			} elseif (!is_writable($cache)) {
				$this->JSCache = 0;
			} else {
				$this->JSCache = 1;
			}
		}
		
		//from the ThemsAndStyleForm
		function DefineStyles($ThemePath) {
			$StyleRoot = $ThemePath.'styles/';
			$FolderHandle = @opendir($StyleRoot);
			if (!$FolderHandle) {
				$this->Context->WarningCollector->Add(str_replace("//1", $StyleRoot, $this->Context->GetDefinition("ErrOpenDirectoryStyles")));
			} else {
				$this->_Styles = array();
         
				// Loop through each file
				while (false !== ($Item = readdir($FolderHandle))) {
				// Retrieve style names (folders which are not system folders or hidden folders
					if (!in_array($Item, array('.', '..'))
						&& is_dir($StyleRoot.$Item)
						&& substr($Item, 0, 1) != '_'
						&& substr($Item, 0, 1) != '.') $this->_Styles[] = $Item;
         		}
			}
		}
	}

	class VanillaPackerSettings extends PostBackControl {
		var $ConfigurationManager;
		var $Checker;

		function VanillaPackerSettings(&$Context) {
			$this->Name = 'VanillaPackerSettings';
			$this->ValidActions = array('PackerSettings', 'SavePackerSettings');
			$this->Constructor($Context);
			if (!$this->Context->Session->User->Permission('PERMISSION_CHANGE_APPLICATION_SETTINGS')) {
				$this->IsPostBack = 0;
			} elseif( $this->IsPostBack ) {
				$this->Checker = new CheckPackerInstallation($this->Context);
				$SettingsFile = $this->Context->Configuration['APPLICATION_PATH'].'conf/settings.php';
				$this->ConfigurationManager = $this->Context->ObjectFactory->NewContextObject($this->Context, 'ConfigurationManager');		
				if ($this->PostBackAction == 'SavePackerSettings') {
					if($this->IsValidFormPostBack()) {

						$this->ConfigurationManager->GetSettingsFromForm($SettingsFile);
						$this->ConfigurationManager->DefineSetting('PACKER_ON', ForceIncomingBool('PACKER_ON', 0), 0);
						$this->ConfigurationManager->DefineSetting('PACKER_DISABLE_GZIP', ForceIncomingBool('PACKER_DISABLE_GZIP', 0), 0);						
						if ($this->ConfigurationManager->SaveSettingsToFile($SettingsFile)) {
							header('Location: '.GetUrl($this->Context->Configuration, 'settings.php', '', '', '', '', 'PostBackAction=PackerSettings&Success=1'));
						} else {
							$this->PostBackAction = 'PackerSettings';
						}
					}
				}
			}
			$this->CallDelegate('Constructor');
		}

		function Render() {
			if ($this->IsPostBack) {
				$this->CallDelegate('PreRender');
				$this->PostBackParams->Clear();
				$this->PostBackParams->Set('PostBackAction', 'SavePackerSettings');
				//if ($this->PostBackAction == 'PackerSettings') {
					echo '
					<div id="Form" class="Account PackerSettings">';
					if (ForceIncomingInt('Success', 0)) echo '<div id="Success">'.$this->Context->GetDefinition('ChangesSaved').'</div>';
					echo '
						<fieldset>
							<legend>'.$this->Context->GetDefinition("PackerSettings").'</legend>
							'.$this->Get_Warnings().'
							'.$this->Get_PostBackForm('frmPackerSettings').'
							<p>'.$this->Context->GetDefinition("PackerSettingsNotes").'</p>
							<ul>
								<li>
									<p><span>'.GetDynamicCheckBox('PACKER_ON', 1, $this->ConfigurationManager->GetSetting('PACKER_ON'), '', $this->Context->GetDefinition('PackerOn')).'</span></p>
									<p class="Description">'.$this->Context->GetDefinition('PackerOnNotes').'</p>
								</li>
								<li>
									<p><span>'.GetDynamicCheckBox('PACKER_DISABLE_GZIP', 1, $this->ConfigurationManager->GetSetting('PACKER_DISABLE_GZIP'), '', $this->Context->GetDefinition('PackerDisableGzip')).'</span></p>
									<p class="Description">'.$this->Context->GetDefinition('PackerDisableGzipNotes').'</p>
								</li>
							</ul>
							<div class="Submit">
								<input type="submit" name="btnSave" value="'.$this->Context->GetDefinition('Save').'" class="Button SubmitButton" />
								<a href="'.GetUrl($this->Context->Configuration, $this->Context->SelfUrl).'" class="CancelButton">'.$this->Context->GetDefinition('Cancel').'</a>
							</div>
							</form>
						</fieldset>';
						echo '<fieldset>
							<legend>'.$this->Context->GetDefinition("PackerCheckPatch").'</legend>
							<form id="frmPackerChecker" method="post" action="http://eclipse.localhost/Vanilla-packer/settings.php">
							<h2>'.$this->Context->GetDefinition('PackerCheckInstallation').'</h2>
							<ul>
								<li>';
							if (count($this->Checker->MD5Error) > 0){
								echo '<p class="Description BadMD5">
										<img src="'. $this->Context->StyleUrl .'ico.alert.gif" alt="'.$this->Context->GetDefinition('PackerIconAlert').'" style="vertical-align: bottom" />
										 '. $this->Context->GetDefinition('PackerInstallationError') .'
										</p>
										<ul>';
								foreach ($this->Checker->MD5Error as $file) {
									echo '<li class="BadMD5">'. $file . '</li>';
								}
								echo '</ul>';	
							} else {
								echo '<p class="Description GoodMD5">
										<img src="'. $this->Context->StyleUrl .'ico.check.gif" alt="'.$this->Context->GetDefinition('PackerIconCheck').'" style="vertical-align: bottom" />
										 '. $this->Context->GetDefinition('PackerUptoDate') .'
										</p>';
							}
							echo '</li></ul>
							<h2>'.$this->Context->GetDefinition('PackerCheckStyle').'</h2>
								<p>'.$this->Context->GetDefinition("PackerCheckStyleNotes").'</p>
							<ul>';
							foreach ($this->Checker->Styles as $Style => $result){
								echo '<li><p>'.$Style.': </p><ul>
											<li><p>';
								if ($result['cache']['error']){
									echo '<img src="'. $this->Context->StyleUrl .'ico.alert.gif" alt="'.$this->Context->GetDefinition('PackerIconAlert').'" style="vertical-align: bottom" /> '
									. $result['cache']['message'];
								} else {
									echo '<img src="'. $this->Context->StyleUrl .'ico.check.gif" alt="'.$this->Context->GetDefinition('PackerIconCheck').'" style="vertical-align: bottom" /> '
									. $this->Context->GetDefinition('PackerCacheOk');
								}
								echo '</p>
								</li>
								<li>
									<p>';
								if ($result['packer']['error']){
									echo '<img src="'. $this->Context->StyleUrl .'ico.alert.gif" alt="'.$this->Context->GetDefinition('PackerIconAlert').'" style="vertical-align: bottom" /> '
									. $result['packer']['message'];
								} else {
									echo '<img src="'. $this->Context->StyleUrl .'ico.check.gif" alt="'.$this->Context->GetDefinition('PackerIconCheck').'" style="vertical-align: bottom" /> '
									. $this->Context->GetDefinition('PackerPackerOk');
								}
								echo '</p>
								</li>
								</ul>
								</li>';
							}
							echo '</ul>
								<h2>'.$this->Context->GetDefinition('PackerCheckJS').'</h2>
								<ul><li>';
							if ($this->Checker->JSCache == -1){
								echo '<p class="Description BadMD5">
										<img src="'. $this->Context->StyleUrl .'ico.alert.gif" alt="'.$this->Context->GetDefinition('PackerIconAlert').'" style="vertical-align: bottom" />
										 '. $this->Context->GetDefinition('PackerNoJSCache') .'
										</p>';
							} elseif ($this->Checker->JSCache == 0) {
								echo '<p class="Description BadMD5">
										<img src="'. $this->Context->StyleUrl .'ico.alert.gif" alt="'.$this->Context->GetDefinition('PackerIconAlert').'" style="vertical-align: bottom" />
										 '. $this->Context->GetDefinition('PackerJSCacheNotWritable') .'
										</p>';
							} else {
								echo '<p class="Description GoodMD5">
										<img src="'. $this->Context->StyleUrl .'ico.check.gif" alt="'.$this->Context->GetDefinition('PackerIconCheck').'" style="vertical-align: bottom" />
										 '. $this->Context->GetDefinition('PackerJSCacheOk') .'
										</p>';
							}
							echo '</li></ul>
							</form>
						</fieldset>
					</div>
					';
				//}
				$this->CallDelegate('PostRender');
			}
		}
	}

	$VanillaPackerSettings = $Context->ObjectFactory->NewContextObject($Context, 'VanillaPackerSettings');
	$Page->AddRenderControl($VanillaPackerSettings, $Configuration["CONTROL_POSITION_BODY_ITEM"] + 1);

	$ExtensionOptions = $Context->GetDefinition('ExtensionOptions');
	$Panel->AddList($ExtensionOptions, 100);
	$Panel->AddListItem($ExtensionOptions, $Context->GetDefinition('PackerSettings'), GetUrl($Context->Configuration, 'settings.php', '', '', '', '', 'PostBackAction=PackerSettings'));
}

?>